package com.xuanzheng.company.servlet;

import com.google.gson.Gson;
import com.xuanzheng.company.entity.SystemApplication;
import com.xuanzheng.company.entity.User;
import com.xuanzheng.company.service.SystemApplicationService;
import com.xuanzheng.company.service.impl.SystemApplicationServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/submitApplication")
public class SubmitApplicationServlet extends HttpServlet {
    private final SystemApplicationService applicationService = new SystemApplicationServiceImpl();
    private final Gson gson = new Gson();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        
        // 检查是否是Ajax请求
        boolean isAjaxRequest = "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
        
        if (isAjaxRequest) {
            response.setContentType("application/json;charset=UTF-8");
        } else {
            response.setContentType("text/html;charset=UTF-8");
        }
        
        PrintWriter out = response.getWriter();
        Map<String, Object> result = new HashMap<>();
        
        // 输出所有请求参数作为调试信息
        System.out.println("======= 接收到申请提交请求 =======");
        System.out.println("Content-Type: " + request.getContentType());
        System.out.println("是否Ajax请求: " + isAjaxRequest);
        
        Enumeration<String> paramNames = request.getParameterNames();
        while (paramNames.hasMoreElements()) {
            String paramName = paramNames.nextElement();
            String paramValue = request.getParameter(paramName);
            System.out.println("参数: " + paramName + " = " + paramValue);
        }
        
        // 检查用户会话
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("user") == null) {
            if (isAjaxRequest) {
                result.put("success", false);
                result.put("message", "请先登录");
                out.write(gson.toJson(result));
            } else {
                response.sendRedirect("index.html");
            }
            return;
        }
        
        // 获取当前用户
        User user = (User) session.getAttribute("user");
        System.out.println("当前用户: " + user.getId() + ", 角色: " + user.getRole());
        
        // 检查用户角色，必须是公司负责人
        if (user.getRole() != 1) {
            if (isAjaxRequest) {
                result.put("success", false);
                result.put("message", "只有公司负责人可以提交系统使用申请");
                out.write(gson.toJson(result));
            } else {
                response.sendRedirect("manager_home.html?error=onlyManagerCanSubmit");
            }
            return;
        }
        
        // 检查用户是否已有待审核或已通过的申请
        int applicationStatus = applicationService.getUserApplicationStatus(user.getId());
        System.out.println("用户申请状态: " + applicationStatus);
        
        if (applicationStatus == 0 || applicationStatus == 1) {
            String message = applicationStatus == 0 ? "您已有一个待审核的申请" : "您的申请已通过，无需再次申请";
            if (isAjaxRequest) {
                result.put("success", false);
                result.put("message", message);
                out.write(gson.toJson(result));
            } else {
                response.sendRedirect("manager_home.html?error=" + java.net.URLEncoder.encode(message, "UTF-8"));
            }
            return;
        }
        
        // 获取申请参数
        String reason = request.getParameter("reason");
        System.out.println("申请原因: " + reason);
        
        // 验证参数
        if (reason == null || reason.trim().isEmpty()) {
            if (isAjaxRequest) {
                result.put("success", false);
                result.put("message", "申请原因不能为空");
                out.write(gson.toJson(result));
            } else {
                response.sendRedirect("manager_home.html?error=reasonEmpty");
            }
            return;
        }
        
        // 创建新申请
        SystemApplication application = new SystemApplication();
        application.setUserId(user.getId());
        application.setUserName(user.getName());
        application.setUserPhone(user.getPhone());
        application.setCompanyName(user.getCompanyName());
        application.setCompanyCreditCode(user.getCompanyCreditCode());
        application.setReason(reason);
        
        // 提交申请
        boolean success = applicationService.submitApplication(application);
        System.out.println("申请提交结果: " + (success ? "成功" : "失败"));
        
        if (success) {
            if (isAjaxRequest) {
                result.put("success", true);
                result.put("message", "申请提交成功，请等待审核");
                out.write(gson.toJson(result));
            } else {
                response.sendRedirect("manager_home.html?success=applicationSubmitted");
            }
        } else {
            if (isAjaxRequest) {
                result.put("success", false);
                result.put("message", "申请提交失败，请稍后重试");
                out.write(gson.toJson(result));
            } else {
                response.sendRedirect("manager_home.html?error=submitFailed");
            }
        }
    }
} 